package dp.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

public class JdbcTemplate extends org.springframework.jdbc.core.JdbcTemplate {
	public List<Map> getList(String sql, Object[] param){
		return super.query(sql, param, new MapRowMapper());
	}
	
	/**
	 * 返回Map，列名小写
	 * @param sql
	 * @param param
	 * @return
	 */
	public Map getMap(String sql, Object[] param){
		List<Map> list = getList(sql, param);
		if(list.size()>0){
			return list.get(0);
		}
		else{
			return null;
		}
	}
	
	/**
	 * 用于取一个值的SQL，比如count、sum
	 * @param sql
	 * @param param
	 * @param clazz
	 * @return
	 */
	public <T> List<T> getList(String sql, Object[] param, Class<T> clazz){
		return super.query(sql, param, new ObjectRowMapper());
	}
	
	public <T> T getObject(String sql, Object[] param, Class<T> clazz){
		List<T> list = getList(sql, param, clazz);
		if(list.size()>0){
			return list.get(0);
		}
		else{
			return null;
		}
	}

	protected class MapRowMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			Map item = new HashMap(columnCount);
			for (int i = 1; i <= columnCount; i++) {
				String key = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
				Object obj = JdbcUtils.getResultSetValue(rs, i);
				item.put(key, obj);
			}
			return item;
		}
	}
	
	protected class ObjectRowMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			return JdbcUtils.getResultSetValue(rs, 1);
		}
	}
}
